﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;

namespace Evan.Member
{
    /// <summary>
    /// 管理员管理类
    /// </summary>
    public static class Administrator
    {

        /// <summary>
        /// 缓存管理员信息
        /// </summary>
        /// <param name="AdminInfo"></param>
        public static void CacheAdminInfo(Dictionary<string, object> AdminInfo)
        {
            //管理员登录标识
            Evan.Common.CacheHelp.Insert_NoAbsolute_Rank("admin-" + Common.CommFun.ReturnSessionID(), AdminInfo, Evan.Common.CacheHelp.CacheTimeOut, Evan.Common.CacheHelp.GetRank(6));
            //顺便将管理员的管理权限拿出来 存一下
            Evan.Common.CacheHelp.Insert_NoAbsolute_Rank("role-" + Common.CommFun.ReturnSessionID(), GetAdminRoleValue(), Evan.Common.CacheHelp.CacheTimeOut, Evan.Common.CacheHelp.GetRank(6));
            //当前登录的管理员名称 用于当前登录的管理员禁止重复登录
            Evan.Common.CacheHelp.Insert_NoAbsolute_Rank(AdminInfo["Name"].ToString(), AdminInfo["Name"].ToString(), Evan.Common.CacheHelp.CacheTimeOut, Evan.Common.CacheHelp.GetRank(6));
            //重新登录的话 , 要删掉锁定信息
            Evan.Common.CacheHelp.Del("admin-lock");
            dynamic SystemConfig = Common.SysComm.GetSystemConfig();
            if (Convert.ToInt32(SystemConfig.AdminLoginIsCookie) == 1)
            {
                string AdminInfoStr = Common.CommFun.GetTimeStamp() + " " + AdminInfo["Name"] + " " + AdminInfo["Pwd"] + " " + Common.CommFun.GetTimeStamp();
                AdminInfoStr = Evan.Encrypt.DESEncrypt.Encrypt(AdminInfoStr); //Des加密
                //拿到cookie里面的信息 , 存起账号密码信息
                //Evan.Common.CommFun.WriteCookie("AdminLoginCookie", AdminInfoStr, Convert.ToInt32(SystemConfig.AdminCookieExpires));
                Evan.Common.CommFun.AddCookie("AdminLoginCookie", AdminInfoStr, Convert.ToDouble(SystemConfig.AdminCookieExpires));
            }
        }

        /// <summary>
        /// 清除管理员的缓存
        /// </summary>
        public static void ClearAdminInfo()
        {
            string adminName = GetAdminName();
            Common.CacheHelp.Del("admin-lock");
            Common.CacheHelp.Del(adminName);
            Common.CacheHelp.Del("admin-" + Evan.Common.CommFun.ReturnSessionID());
            Common.CacheHelp.Del("role-" + Evan.Common.CommFun.ReturnSessionID());
            Common.CacheHelp.Del("superAdmin-" + Evan.Common.CommFun.ReturnSessionID());
            Common.CacheHelp.Del("systemAdmin-" + Evan.Common.CommFun.ReturnSessionID());
            Common.CommFun.DelCookie("AdminLoginCookie");
        }

        /// <summary>
        /// 管理员是否已经登录
        /// </summary>
        /// <returns></returns>
        public static bool IsAdminLogin()
        {
            //拿到登录状态
            bool IsLogin = Evan.Common.CacheHelp.GetValue("admin-" + Common.CommFun.ReturnSessionID()) == null ? false : true;
            //如果是未登录状态 才去找Cookie
            if (!IsLogin)
            {
                dynamic SystemConfig = Common.SysComm.GetSystemConfig();
                if (Convert.ToInt32(SystemConfig.AdminLoginIsCookie) == 1)
                {
                    //使用了Cookie辅助登录
                    //拿到cookie里面的信息 , 重新登录
                    string AdminInfoStr = Evan.Common.CommFun.GetCookie("AdminLoginCookie");
                    if (!string.IsNullOrEmpty(AdminInfoStr))
                    {
                        //不为空
                        try
                        {
                            AdminInfoStr = Evan.Encrypt.DESEncrypt.Decrypt(AdminInfoStr);
                            string[] Info = AdminInfoStr.Split(' ');
                            Evan.DataBase.DbOperat db = new Evan.DataBase.DbOperat("Administrator");
                            dynamic model = db.GetModel_1(" Name=@Name and Pwd=@Pwd ", Info[1], Info[2]);
                            if (model != null)
                            {
                                if (model.States == 1)
                                {
                                    //登录成功
                                    Dictionary<string, object> admin = Evan.Model.ConvertModel.ConvertToDictionary(model);
                                    Member.Administrator.CacheAdminInfo(admin);
                                    return true;
                                }
                                else
                                {
                                    return false;
                                }
                            }
                            else
                            {
                                return false;
                            }
                        }
                        catch (Exception ex)
                        {
                            //出错后记录异常信息
                            Evan.SystemLog.MemLog.AddExLog2("判断是否管理员登录的时候 , 从Cookie拿到登录信息失败", null, ex.ToString());
                            return false;
                        }
                    }
                    else
                    {
                        //cookie 是空的   返回未登录
                        return false;
                    }
                    
                }
                else
                {
                    return IsLogin;
                }
            }
            else {
                return IsLogin;
            }
        }


        /// <summary>
        /// 锁定管理员
        /// </summary>
        /// <returns></returns>
        public static void AdminLock()
        {
            //管理员锁定标识
            Evan.Common.CacheHelp.Insert_NoAbsolute_Rank("admin-lock", "1", Evan.Common.CacheHelp.CacheTimeOut, Evan.Common.CacheHelp.GetRank(6));
        }
        /// <summary>
        /// 管理员是否已经锁定
        /// </summary>
        /// <returns></returns>
        public static bool IsAdminLock()
        {
            if (Evan.Common.CacheHelp.GetValue("admin-lock") == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 获取管理员ID
        /// </summary>
        /// <returns></returns>
        public static string GetAdminId()
        {
            Dictionary<string, object> Info = GetAdminInfoFromCache();
            if (Info != null)
            {
                return Info["Id"].ToString();
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 查看当前管理员是否已经登录
        /// </summary>
        /// <param name="adminName">管理员登录名</param>
        /// <returns>true=已经登录  false=没有登录</returns>
        public static bool CheckIsLoginByAdminName(string adminName)
        {
            if (Evan.Common.CacheHelp.GetValue(adminName) == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 获取管理员Name
        /// </summary>
        /// <returns></returns>
        public static string GetAdminName()
        {
            Dictionary<string, object> Info = GetAdminInfoFromCache();
            if (Info != null)
            {
                return Info["Name"].ToString();
            }
            else {
                return "";
            }
        }
        /// <summary>
        /// 获取管理员所有信息
        /// </summary>
        /// <returns></returns>
        public static Dictionary<string, object> GetAdminInfoFromCache()
        {
            if (IsAdminLogin())
            {
                return (Dictionary<string, object>)Evan.Common.CacheHelp.GetValue("admin-" + Common.CommFun.ReturnSessionID());
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 从数据库中获取管理员权限集
        /// </summary>
        /// <returns></returns>
        public static string GetAdminRoleValue()
        {
            if (IsAdminLogin())
            {
                Dictionary<string, object> AdminInfo = GetAdminInfoFromCache();
                //SystemLog.MemLog.AddLog("测试111", AdminInfo["RoleId"].ToString());
                string RoldId = AdminInfo["RoleId"].ToString().Trim(',');
                List<dynamic> RoleList = new Evan.DataBase.DbOperat("Roles").GetList_2(0, "", "States=1 and Id in(" + RoldId + ")", "Id Desc");
                string RoleListStr = "";
                foreach (var item in RoleList)
                {
                    //SystemLog.MemLog.AddLog("权限内容111", item.Content.ToString());
                    if (!string.IsNullOrEmpty(item.Content))
                    {
                        RoleListStr += item.Content;
                    }
                    if (Convert.ToInt32(item.IsSystem) == 1) //是系统管理员
                    {
                        Evan.Common.CacheHelp.Insert_NoAbsolute_Rank("systemAdmin-" + Common.CommFun.ReturnSessionID(), "1", Evan.Common.CacheHelp.CacheTimeOut, Evan.Common.CacheHelp.GetRank(6));
                    }
                    if (Convert.ToInt32(item.IsSuperAdmin) == 1) //是超级管理员
                    {
                        Evan.Common.CacheHelp.Insert_NoAbsolute_Rank("superAdmin-" + Common.CommFun.ReturnSessionID(), "1", Evan.Common.CacheHelp.CacheTimeOut, Evan.Common.CacheHelp.GetRank(6));
                    }
                }
                return RoleListStr;
            }
            return "";
        }

        /// <summary>
        /// 当前管理员是否超级管理员
        /// </summary>
        /// <returns></returns>
        public static bool IsSuperAdmin()
        {
            if (IsAdminLogin())
            {
                object isSuperAdmin = Evan.Common.CacheHelp.GetValue("superAdmin-" + Common.CommFun.ReturnSessionID());
                if (isSuperAdmin != null)
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 当前管理员是否系统管理员
        /// </summary>
        /// <returns></returns>
        public static bool IsSystemAdmin()
        {
            if (IsAdminLogin())
            {
                object isSystemAdmin = Evan.Common.CacheHelp.GetValue("systemAdmin-" + Common.CommFun.ReturnSessionID());
                if (isSystemAdmin != null)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 获得管理员的密码 - 明文密码
        /// </summary>
        /// <returns></returns>
        public static string GetCurAdminPwd()
        {
            string pwd = GetAdminInfoFromCache()["Pwd"].ToString();
            return Common.CommFun.RePwd(pwd);
        }
   
        /// <summary>
        /// 验证用户是否有此项权限
        /// </summary>
        /// <param name="type">验证类型 1=常规类型  0=系统类型</param>
        /// <param name="classId">栏目id 如果是系统类型 classid=0</param>
        /// <param name="page">相应的页面 database filemanager role admin syslog channel system</param>
        /// <param name="action">相应的操作 add delete update view 如果是page(系统类型) 这里为空</param>
        /// <returns></returns>
        public static bool HasRole(int type, string classId, string page, string action)
        {
            bool Role = false;
            
            if (string.IsNullOrEmpty(Evan.Common.CommFun.ReturnSessionID()))
            {
                return false;    
            }

            //调试Session是否为空导致权限验证失败
            //SystemLog.MemLog.AddExLog2("验证权限 , 方法 Evan.Administrator.HasRole ", null, "SessionID=" + Evan.Common.CommFun.ReturnSessionID());


            string RoleStr = Common.CacheHelp.GetValue("role-" + Evan.Common.CommFun.ReturnSessionID()).ToString();
            if (IsSuperAdmin())
            {
                //如果是超级管理员  ,  直接放行
                Role = true;
            }
            else if (IsSystemAdmin())
            {
                if (type == 1)
                {
                    //如果是常规类型  直接放行
                    Role = true;
                }
                else
                {
                    if (RoleStr.IndexOf("," + page + "_" + classId + ",", StringComparison.OrdinalIgnoreCase) > -1) //有权限
                    {
                        Role = true;
                    }
                }
            }
            else
            {
                //普通管理员 开始判断
                if (type == 1)
                {
                    // 常规类型
                    if (RoleStr.IndexOf("," + action + "_" + classId + ",", StringComparison.OrdinalIgnoreCase) > -1)
                    {
                        Role = true;
                    }
                }
                else
                {
                    //系统类型
                    if (RoleStr.IndexOf("," + page + "_" + classId + ",", StringComparison.OrdinalIgnoreCase) > -1) //有权限
                    {
                        Role = true;
                    }
                }
            }
            return Role;
        }


    }
}
